/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { omitBy } from 'lodash';
import { useEffect, useMemo, useState } from 'react';
import { ChildProjectionCommandProps } from './types';

type ProjectMode = 'Normal' | 'Direction';

type FormData = {
  surface?: pickedFaceData;
  curve?: pickedLineData;
  mode: ProjectMode;
  vector?: pickedLineData | pickedFaceData;
};

type Params = {
  mode: ProjectMode;
  surface: string;
  curve: string;
  vector?: string;
};

export function CurveProjection({
  onClose,
  props,
  editDxid,
}: ChildProjectionCommandProps) {
  const initData: FormData = {
    mode: 'Normal',
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { surface, curve, mode, vector } = params;

    await initEditDependency([surface, curve, vector]);

    setFormData({
      mode,
      surface: picker.generatePickObjByPickID(surface) as pickedFaceData,
      curve: picker.generatePickObjByPickID(curve) as pickedLineData,
      vector:
        vector &&
        (picker.generatePickObjByPickID(vector) as
          | pickedFaceData
          | pickedLineData),
    });
  }, [editDxid]);

  const isFormDataValid = () => {
    const { curve, surface, mode, vector } = formData;

    if (mode === 'Normal') {
      return curve != null && surface != null;
    }

    if (mode === 'Direction') {
      return curve != null && surface != null && vector != null;
    }

    return false;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-curve-projection', {
      commandName: 'CreateCurve',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = async (preview: boolean) => {
    const { curve, surface, mode, vector } = formData;

    await confirmCommand(
      {
        type: 'Project',
        a: {
          mode,
          curve: curve.edgeId,
          surface: surface.meshId,
          vector: mode === 'Direction' ? getIdOfPickedObj(vector) : null,
        },
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const schema: RJSFSchema = useMemo(() => {
    const properties = omitBy(
      {
        mode: {
          title: '模式',
          type: 'string',
          oneOf: [
            {
              type: 'string',
              title: '法线',
              const: 'Normal',
            },
            {
              type: 'string',
              title: '方向',
              const: 'Direction',
            },
          ],
          default: 'Normal',
        },
        surface: {
          type: 'string',
          format: PickInputRJSFFormat.PickSurface,
        },
        curve: {
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        vector:
          formData.mode === 'Direction'
            ? {
                type: 'string',
                format: PickInputRJSFFormat.PickDirection,
              }
            : null,
      },
      (val) => val == null,
    );

    return {
      type: 'object',
      properties,
    } as RJSFSchema;
  }, [formData.mode]);

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      onCancel={onClose}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        surface: {
          'ui:placeholder': '请输入投影面',
          'ui:autofocus': true,
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:options': {
            allowInfiniteLine: true,
          },
        },
        vector: {
          'ui:placeholder': '请输入方向',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}
